package database;

import java.sql.*;

import comun.Constantes.*;

public class DBaccess {

	private Connection conec;
	private static DBaccess instance = null;

	public static DBaccess getInstance() {

		if (instance == null)
			instance = new DBaccess();
		return instance;
	}

	public void establecerConexion() {
		try {
			Class.forName("org.sqlite.JDBC");
		} catch (ClassNotFoundException e) {
			e.printStackTrace();
		}
		try {
			conec = DriverManager
					.getConnection("jdbc:sqlite:files/DBVideoClub.sqlite.s3db");
		} catch (SQLException e) {
			e.printStackTrace();
		}
	}

	public ResultSet leerTodo(String T) throws SQLException {

		Statement stat = conec.createStatement();
		ResultSet rs = stat.executeQuery("SELECT * FROM " + T + ";");

		return rs;

	}

	public ResultSet leerOrdenar(String T, String condicion)
			throws SQLException {

		Statement stat = conec.createStatement();
		ResultSet rs = stat.executeQuery("SELECT * FROM " + T + " ORDER BY "
				+ condicion + " DESC ;");

		return rs;
	}

	public void insertar(String S) throws SQLException {

		PreparedStatement stat = conec.prepareStatement(S);

		stat.executeUpdate();

	}

	public void actualizar(tablas T, String nuevosValores, String where)
			throws SQLException {
		Statement stat = conec.createStatement();

		String actualizar = "UPDATE " + T + " " + " SET " + nuevosValores
				+ " WHERE " + where + ";";
		stat.executeUpdate(actualizar);

	}

	public void borrar(tablas T) throws SQLException {

		Statement stat = conec.createStatement();

		String borrar = "DELETE FROM " + T + ";";
		stat.executeUpdate(borrar);

	}

	public void cerrarConexion() {
		try {
			conec.close();
		} catch (SQLException e) {
			e.printStackTrace();
		}

	}

	public ResultSet leerMisFavoritos(String T, String condicion)
			throws SQLException {
		Statement stat = conec.createStatement();
		ResultSet rs = stat.executeQuery("SELECT * FROM " + T + "WHERE "
				+ condicion + ";");

		return rs;

	}

}
